package com.web.demo.demo;

import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;
import java.util.Arrays;

/**
 * @author sw
 * @create 2023-05-18 12:59
 */
public class OtherClassTest {

    public static void main(String[] args) {
        Enhancer enhancer = new Enhancer();
        enhancer.setSuperclass(OtherClass.class);
        enhancer.setCallback(new MethodInterceptor() {
            @Override
            public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
                Arrays.stream(objects).forEach(System.out::println);
                System.out.println("调用之前");
                // 注意这里调用的是invokeSuper,还有一个方法invoke调用的代理本身的方法，会造成Stack Overflow
                Object result = methodProxy.invokeSuper(o, objects);
                System.out.println("调用之后");
                return result;
            }
        });
        OtherClass otherClass = (OtherClass) enhancer.create();
        System.out.println("代理类是：" + otherClass.getClass().getSimpleName());
        System.out.println("代理的父类是：" + otherClass.getClass().getSuperclass().getSimpleName());
        otherClass.test();
        otherClass.setName("bbbb");
    }
}
